package com.caipu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caipu.dto.DishDetailDTO;
import com.caipu.entity.UserFavorite;
import com.caipu.mapper.UserFavoriteMapper;
import com.caipu.service.DishService;
import com.caipu.service.UserFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite> implements UserFavoriteService {
    
    @Autowired
    private DishService dishService;
    
    @Override
    public boolean addFavorite(Long userId, Long dishId) {
        // 检查是否已收藏
        if (isFavorite(userId, dishId)) {
            return false;
        }
        
        UserFavorite favorite = new UserFavorite();
        favorite.setUserId(userId);
        favorite.setDishId(dishId);
        favorite.setCreateTime(LocalDateTime.now());
        
        return save(favorite);
    }
    
    @Override
    public boolean removeFavorite(Long userId, Long dishId) {
        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("dish_id", dishId);
        
        return remove(queryWrapper);
    }
    
    @Override
    public boolean isFavorite(Long userId, Long dishId) {
        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("dish_id", dishId);
        
        return count(queryWrapper) > 0;
    }
    
    @Override
    public Page<DishDetailDTO> getFavoriteDishesByUser(Long userId, int page, int size) {
        // 获取用户收藏的菜品ID列表
        List<Long> dishIds = getFavoriteDishIds(userId);
        
        if (dishIds.isEmpty()) {
            return new Page<>(page, size);
        }
        
        // 通过菜品服务获取菜品详情
        return dishService.getDishesByIds(dishIds, page, size);
    }
    
    @Override
    public List<Long> getFavoriteDishIds(Long userId) {
        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("create_time");
        
        List<UserFavorite> favorites = list(queryWrapper);
        return favorites.stream()
                .map(UserFavorite::getDishId)
                .collect(Collectors.toList());
    }
}